package com.clever.mall.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author ChenWang
 * @className UploadFileUtil
 * @date 2020/11/09 11:42
 * @since JDK 1.8
 */
public class UploadFileUtil {

    private static final String DATA_TIME_PATTERN = "yyyyMMddHHmmss";
    private static final String DATA_TIME = "yyyyMMdd";
    private static final String ROOTPATH = "D:\\workbench\\livePractice\\b_twoSS\\day62-project-item\\project-item\\src\\main\\webapp";

    public static String uploadFile(MultipartFile multipartFile) throws IOException {
        /* 获取文件名 */
        String oldName = multipartFile.getOriginalFilename();
        if("".equals(oldName)||oldName==null){
            throw new IOException("非法文件");
        }
        /* 获取文件类型*/
        String type = oldName.substring(oldName.lastIndexOf(".")+1);
        /* 以指定格式获取当前时间的字符串*/
        String format = DateFormatUtils.format(new Date(), DATA_TIME);
        /* 服务器上的文件目录的路径*/
        String path = type+ File.separator+format;
        File file = new File(ROOTPATH+File.separator+path);
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName = getFileName(type);
        /* 上传文件到指定的地址 */
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),new File(file,fileName));
        return path+fileName;
    }
    public static String getFileName(String type){
        /* 以指定格式获取当前时间的字符串*/
        String format = DateFormatUtils.format(new Date(), DATA_TIME_PATTERN);
        return String.format("%s%s%s%s",type.toUpperCase(),format,".",type);
    }
}
